import React, { useState, useMemo } from 'react';
import s from './style.module.css';
// import SelectAnt from '@/components/SelectAnt';
import { Table, Datetime, Button, Input, Dialog, Pagination, Select } from '@knownsec/react-component';
import moment from 'moment';
import { datetime } from '../../../common/formatter';
import { vulEnums, vulList } from '~/API';
import { useLocation } from 'react-router-dom';
import { GetQueryString } from '@/common/constant';
import cn from 'classnames';

const defaultSearch = {
  keyword: '',
  vuln_type: null,
  time: [],
  severity: null,
  page: 1,
  count: 10,
};
const typeObj = { 严重: 'yz', 高危: 'gw', 中危: 'zw', 低危: 'dw' };
export default function bugStore() {
  const [refe, setRef] = useState(false);
  const [enums, setEnums] = useState([]);
  const [searchInfo, setSearchInfo] = useState(defaultSearch);
  const [tableData, setTableData] = useState({ data: [], total: 0 });
  const [loading, setLoading] = useState(true);
  const search = useLocation().search;
  const name = GetQueryString(search, 'name');

  const columns = [
    {
      title: '漏洞名称',
      dataIndex: 'vuln_name',
      className: s.w_30,
    },
    {
      title: '漏洞等级',
      dataIndex: 'level',
      className: s.w_8,
      render: (e) => {
        return <span className={s[typeObj[e]]}>{e||'--'}</span>;
      },
    },
    {
      title: '漏洞类型',
      dataIndex: 'vuln_type',
      className: s.w_8,
      render:(e)=>{return e||'--'}
    },
    {
      title: '更新时间',
      dataIndex: 'updated_at',
      render: (e) => {
        return <span>{datetime(e)|| '--'}</span>;
      },
    },
    // {
    //   title: '标签',
    //   dataIndex: 'e',
    //   render: (e, row) => {
    //     return (
    //       <div className={s.label}>
    //         {e.map((item) => {
    //           return <span>{item}</span>;
    //         })}
    //       </div>
    //     );
    //   },
    // },
    {
      title: '操作',
      dataIndex: 'option',
      className: s.w_6,
      valueType: 'option',
      render: (e, row) => {
        return (
          <div
            className={s.operation}
            onClick={() => {
              showDialog(row);
            }}
          >
            查看详情
          </div>
        );
      },
    },
  ];
  const getEnums = async (e) => {
    const enums = await vulEnums(e);
    const type = enums.data.vuln_type.map((e) => {
      return { label: e.zh_cn, value: e.zh_cn };
    });
    setEnums(type);
  };
  // const getList = async (e) => {
  //   setLoading(true);
  //   const list = await vulList(e);
  //   setLoading(false);
  //   setTableData({ data: list.data.results.data, total: list.data.results.count });
  // };
  const getList = e => {
    setLoading(true);
    vulList(e).then(list => {
      setLoading(false)
      setTableData({ data: list.data.results.data, total: list.data.results.count });
    })
  }
  const [bugDetailVisible, setBugDetailVisible] = useState(false)
  const [bugDetail, setBugDetail] = useState(null)
  const showDialog = (detail = {}) => {
    setBugDetailVisible(true)
    setBugDetail(detail)
  };
  const onSearch = (e) => {
    let params = { page: 1, count: 10 };
    if (!e) {
      setSearchInfo(defaultSearch);
    } else {
      if (e.page) {
        setSearchInfo({ ...searchInfo, page: e.page, count: e.limit });
        params = { ...searchInfo, page: e.page, count: e.limit };
      } else {
        params = {
          ...searchInfo,
        };
      }
    }
    if (searchInfo.time[0]&&e) {
      let start_time = moment(searchInfo.time[0]._d).format('YYYY-MM-DD 00:00');
      let end_time = moment(searchInfo.time[1]._d).format('YYYY-MM-DD 23:59');
      params = {
        ...params,
        start_time: datetime(new Date(start_time)),
        end_time: datetime(new Date(end_time)),
      };
    } else {
      delete params.time;
    }
    Object.keys(params).forEach((key) => {
      !params[key] && delete params[key];
    });
    setTimeout(() =>{
      getList(params);
    })
  };
  React.useMemo(() => {
    if (name) {
      setSearchInfo({ ...searchInfo, keyword: name });
      getList({ page: 1, count: 10, keyword: name });
    } else {
      onSearch(true);
    }
    getEnums();
  }, []);
  return (
    <div className={s.tableBox}>
      <div className={s.tool}>
        <Select
          pro
          clearable
          value={[searchInfo.severity]}
          placeholder="漏洞等级"
          option={[
            { label: '严重', value: 5 },
            { label: '高危', value: 4 },
            { label: '中危', value: 3 },
            { label: '低危', value: 2 },
            { label: '信息', value: 1 },
          ]}
          className={s.sel}
          onChange={({ selectedItem }) => {
            const e = selectedItem[0]?.value || ''
            setSearchInfo({ ...searchInfo, severity: e });
          }}
        />
        <Select
          pro
          value={[searchInfo.vuln_type]}
          placeholder="漏洞类型"
          searchable
          filterable
          clearable
          option={enums}
          className={s.sel}
          onChange={({ selectedItem }) => {
            const e = selectedItem[0]?.value || ''
            setSearchInfo({ ...searchInfo, vuln_type: e });
          }}
        />
        <Datetime
          pro
          useDefault
          value={searchInfo.time}
          className={s.datetime}
          showTime={false}
          onChange={(e) => {
            const e_ = e ? e : [];
            setSearchInfo({ ...searchInfo, time: e_ });
          }}
        />
        <Input
          pro
          value={searchInfo.keyword}
          autoComplete={'off'}
          className={s.inp}
          placeholder="请输入漏洞名称/标号"
          type="text"
          maxlength={32}
          onChange={(e) => {
            setSearchInfo({ ...searchInfo, keyword: e.value });
          }}
        />
        <Button
          pro
          type="primary"
          onClick={() => {
            onSearch(true);
          }}
        >
          查询
        </Button>
        <Button
          pro
          onClick={() => {
            onSearch(false);
          }}
        >
          重置
        </Button>
      </div>
      <Table 
        refre={refe} 
        columns={columns} 
        className={s.table} 
        tableLoading={loading}
        loadingLabel=""
        data={tableData.data}></Table>
      {tableData.total > 10 && <Pagination
        key={Number(123)}
        className={s.pagination}
        current={searchInfo.page}
        showQuickJumper={{ goButton: true }}
        showSizeChanger={true}
        showTotal={(total) => `共${total}条`}
        pageSize={searchInfo.count}
        pageSizeOptions={['10', '20', '50']}
        total={tableData.total}
        onChange={(page, limit) => {
          onSearch({ page, limit });
        }}
      />}
      <Dialog className={s.w740} title="漏洞详情" visible={bugDetailVisible} 
        confirmText='关闭' cancelText='' 
        onhide={() => setBugDetailVisible(false)} 
        onsubmit={() => setBugDetailVisible(false)} >
        <div className={cn(s.content, s.p24)}>
          <div className={s.nameBox}>
            <div className={s.left}>
              <span>漏洞名称：{bugDetail?.vuln_name}</span>
              <span>发布时间：{datetime(bugDetail?.published_at) || '--'}</span>
              <p className={s.cve}>
                <span>漏洞编号：</span>
                <span className={s.spancCve}>
                  <span>CVE-ID：{bugDetail?.cve[0] || '--'}</span>
                  <span>CNNVD-ID：{bugDetail?.cnnvd[0] || '--'}</span>
                </span>
              </p>
            </div>
            <div className={s.right}>
              <span>漏洞等级：{bugDetail?.level}</span>
              <span>更新时间：{datetime(bugDetail?.updated_at)}</span>
            </div>
          </div>
          <p className={s.titleP}>漏洞影响：</p>
          <span className={s.contentSpan}>{bugDetail?.impact}</span>
          <p className={s.titleP}>漏洞概述：</p>
          <span className={s.contentSpan}>{bugDetail?.description}</span>
          <p className={s.titleP}>影响范围：</p>
          {bugDetail?.zoomeye_count !== 0 ? (
            <span className={s.contentSpan}>
              根据ZoomEye网络空间搜索引擎关键字 {bugDetail?.zoomeye_dork} 对潜在可能目标进行搜索，共得到{' '}
              {bugDetail?.zoomeye_count} 条IP历史记录。
            </span>
          ) : (
            '--'
          )}
          <p className={s.titleP}>建议解决方案：</p>
          <span className={s.contentSpan}>{bugDetail?.recommendation}</span>
          <p className={s.titleP}>参考链接：</p>
          <span className={s.contentSpan}>{bugDetail?.reference[0]}</span>
        </div>
      </Dialog>
    </div>
  );
}
